const tokenUtis = require('../utils/token_utils')
// API 响应基类
class ApiResponse {
    constructor(res) {
        this.res = res;
        this.time = Date.now();
    }

    success(data, message) {
        this.res.status(200).json({
            success: true,
            message: message || 'Operation successful',
            data: data,
            time: this.time
        });
    }

    error(message, code) {
        this.res.status(code || 500).json({
            success: false,
            message: message || 'An error occurred',
            data: '',
            time: this.time
        });
    }

    fail(errData, code) {
        this.res.status(code || 500).json({
            success: false,
            message: errData || 'request failed',
            data: '',
            time: this.time
        });
    }

    validateFailed(param, code) {
        this.res.status(code || 400).json({
            success: false,
            message: param || '参数校验失败 param validateFailed',
            data: '',
            time: this.time
        });
    }

    apiNotFount(message, code) {
        this.res.status(code || 404).json({
            success: false,
            message: message || '接口不存在 api not fount',
            data: '',
            time: this.time
        });
    }

    apiBusy(message, code) {
        this.res.status(code || 700).json({
            success: false,
            message: message || '操作过于频繁 api busy',
            data: '',
            time: this.time
        });
    }

    download(filePath, code) {
        this.res.status(code || 700).download(filePath);
    }

    sendFile(filename, filePath, code) {
        this.res.status(code || 200).sendFile(filename, { root: filePath });
    }

    sendFiredirectle(url, code) {
        this.res.status(code || 200).redirect(url);
    }
}

// 白名单  不带token也可以访问
const whiteList = [
    '/',
]

// token验证拦截
const tokenMiddleware = function tokenMiddleware(req, res, next) {
    if (whiteList.includes(req.path)) return next()
    let apiRes = new ApiResponse(res);
    let token = req.get('Authorization')
    if (token) {
        // 验证中用了截取，采用了Bearer  xxxx 的形式，所以做了截取只保留token部分进行验证
        const result = tokenUtis.verifyToken(token.split(' ')[1])
        if (result) {
            next()
        } else {
            apiRes.validateFailed('登录信息已失效，请重新登录', 400)
        }
    } else {
        apiRes.validateFailed('未携带token', 401)
    }
}

module.exports = { ApiResponse, tokenMiddleware };